import React, { useState, useRef, useEffect } from "react";
import alertService from "../utils/alertService"; // 导入alert服务

interface ImageUploaderProps {
  onImagesSelected: (files: File[]) => void;
  disabled?: boolean;
  maxImages?: number;
  maxSizePerImage?: number; // 单位：MB
  maxTotalSize?: number; // 单位：MB
  externalSelectedImages?: File[]; // 新增：外部控制的已选图片
}

const ImageUploader: React.FC<ImageUploaderProps> = ({
  onImagesSelected,
  disabled = false,
  maxImages = 5,
  maxSizePerImage = 20, // 默认20MB
  maxTotalSize = 100, // 默认100MB
  externalSelectedImages,
}) => {
  const [selectedImages, setSelectedImages] = useState<File[]>([]);
  const [previewUrls, setPreviewUrls] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 监听外部图片状态变化
  useEffect(() => {
    // 如果外部图片状态存在且为空数组，则重置内部状态
    if (
      externalSelectedImages !== undefined &&
      externalSelectedImages.length === 0 &&
      selectedImages.length > 0
    ) {
      // 释放所有预览URL
      previewUrls.forEach((url) => URL.revokeObjectURL(url));
      setSelectedImages([]);
      setPreviewUrls([]);
      setError(null);
    }
    // 新增：处理外部图片列表有内容的情况
    else if (
      externalSelectedImages !== undefined &&
      externalSelectedImages.length > 0
    ) {
      // 检查是否需要更新内部状态(避免不必要的状态更新)
      const needsUpdate =
        externalSelectedImages.length !== selectedImages.length ||
        !externalSelectedImages.every(
          (file, index) =>
            selectedImages[index] &&
            file.name === selectedImages[index].name &&
            file.size === selectedImages[index].size &&
            file.lastModified === selectedImages[index].lastModified
        );

      if (needsUpdate) {
        // 清理现有的预览URL
        previewUrls.forEach((url) => URL.revokeObjectURL(url));

        // 创建新的预览URL
        const newPreviewUrls = externalSelectedImages.map((file) =>
          URL.createObjectURL(file)
        );

        // 更新内部状态
        setSelectedImages(externalSelectedImages);
        setPreviewUrls(newPreviewUrls);
        setError(null);
      }
    }
  }, [externalSelectedImages, selectedImages, previewUrls]);

  // 将MB转换为字节
  const mbToBytes = (mb: number) => mb * 1024 * 1024;

  // 将字节转换为可读格式
  const formatFileSize = (bytes: number): string => {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
    return (bytes / (1024 * 1024)).toFixed(1) + " MB";
  };

  // 计算当前已选图片的总大小
  const calculateTotalSize = (files: File[]): number => {
    return files.reduce((total, file) => total + file.size, 0);
  };

  // 处理文件选择
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    if (!files.length) return;

    // 检查文件类型
    const imageFiles = files.filter((file) => file.type.startsWith("image/"));
    if (imageFiles.length !== files.length) {
      const errorMsg = "只能上传图片文件";
      setError(errorMsg);
      alertService.warning(errorMsg);
      return;
    }

    // 检查是否有重复图片
    const duplicateFiles = imageFiles.filter((newFile) =>
      selectedImages.some(
        (existingFile) =>
          existingFile.name === newFile.name &&
          existingFile.size === newFile.size &&
          existingFile.lastModified === newFile.lastModified
      )
    );

    if (duplicateFiles.length > 0) {
      const errorMsg =
        duplicateFiles.length === 1
          ? `文件 "${duplicateFiles[0].name}" 已存在，已跳过添加`
          : `${duplicateFiles.length} 个重复文件已跳过添加`;
      alertService.warning(errorMsg);

      // 过滤掉重复文件
      const uniqueFiles = imageFiles.filter(
        (newFile) =>
          !selectedImages.some(
            (existingFile) =>
              existingFile.name === newFile.name &&
              existingFile.size === newFile.size &&
              existingFile.lastModified === newFile.lastModified
          )
      );

      // 如果没有新的唯一文件，则直接返回
      if (uniqueFiles.length === 0) {
        return;
      }

      // 继续处理非重复文件
      imageFiles.length = 0;
      imageFiles.push(...uniqueFiles);
    }

    // 检查是否超过最大图片数量限制
    const newTotalImages = selectedImages.length + imageFiles.length;
    if (newTotalImages > maxImages) {
      const errorMsg = `最多只能上传 ${maxImages} 张图片`;
      setError(errorMsg);
      alertService.warning(errorMsg);
      return;
    }

    // 检查单个图片大小
    const oversizedImages = imageFiles.filter(
      (file) => file.size > mbToBytes(maxSizePerImage)
    );
    if (oversizedImages.length > 0) {
      const errorMsg = `图片大小不能超过 ${maxSizePerImage}MB`;
      setError(errorMsg);
      alertService.error(errorMsg);
      return;
    }

    // 检查总大小
    const currentTotalSize = calculateTotalSize(selectedImages);
    const newTotalSize = calculateTotalSize(imageFiles);
    if (currentTotalSize + newTotalSize > mbToBytes(maxTotalSize)) {
      const errorMsg = `所有图片总大小不能超过 ${maxTotalSize}MB`;
      setError(errorMsg);
      alertService.error(errorMsg);
      return;
    }

    // 清除错误
    setError(null);

    // 创建预览URL
    const newPreviewUrls = imageFiles.map((file) => URL.createObjectURL(file));

    // 更新状态
    const newSelectedImages = [...selectedImages, ...imageFiles];
    setSelectedImages(newSelectedImages);
    setPreviewUrls([...previewUrls, ...newPreviewUrls]);

    // 调用回调函数
    onImagesSelected(newSelectedImages);

    // 成功提示
    alertService.success(`已成功添加 ${imageFiles.length} 张图片`);

    // 重置文件输入以允许重新选择相同的文件
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  // 处理图片删除
  const handleRemoveImage = (index: number) => {
    // 释放预览URL
    URL.revokeObjectURL(previewUrls[index]);

    // 创建新的数组，排除要删除的图片
    const newSelectedImages = selectedImages.filter((_, i) => i !== index);
    const newPreviewUrls = previewUrls.filter((_, i) => i !== index);

    // 更新状态
    setSelectedImages(newSelectedImages);
    setPreviewUrls(newPreviewUrls);
    setError(null);

    // 调用回调函数
    onImagesSelected(newSelectedImages);

    // 删除成功提示
    alertService.info("图片已移除");
  };

  // 处理添加图片按钮点击
  const handleAddImageClick = () => {
    if (!disabled && fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  return (
    <div className="w-full">
      {/* 错误提示 */}
      {error && (
        <div className="mb-2 p-2 bg-red-100 text-red-700 rounded-md text-sm">
          {error}
        </div>
      )}

      <div className="flex flex-wrap gap-2">
        {/* 图片预览 */}
        {previewUrls.map((url, index) => (
          <div
            key={index}
            className="relative w-20 h-20 border border-gray-300 dark:border-gray-600 rounded-md overflow-hidden group"
          >
            <img
              src={url}
              alt={`预览图 ${index + 1}`}
              className="w-full h-full object-cover"
            />
            <button
              type="button"
              onClick={() => handleRemoveImage(index)}
              className="absolute top-0 right-0 bg-red-500 text-white p-1 rounded-bl-md opacity-0 group-hover:opacity-100 transition-opacity"
              disabled={disabled}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-3 w-3"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fillRule="evenodd"
                  d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                  clipRule="evenodd"
                />
              </svg>
            </button>
            <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-xs p-0.5 text-center">
              {formatFileSize(selectedImages[index]?.size || 0)}
            </div>
          </div>
        ))}

        {/* 添加图片按钮 */}
        {selectedImages.length < maxImages && (
          <button
            type="button"
            onClick={handleAddImageClick}
            disabled={disabled}
            className={`w-20 h-20 flex flex-col items-center justify-center border-2 border-dashed rounded-md
              ${
                disabled
                  ? "border-gray-300 text-gray-400 cursor-not-allowed"
                  : "border-blue-300 text-blue-500 hover:border-blue-500 hover:text-blue-600 dark:border-blue-700 dark:text-blue-400 dark:hover:border-blue-500"
              }`}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 4v16m8-8H4"
              />
            </svg>
            <span className="text-xs mt-1">添加图片</span>
          </button>
        )}
      </div>

      {/* 隐藏的文件输入 */}
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        accept="image/*"
        multiple
        className="hidden"
        disabled={disabled || selectedImages.length >= maxImages}
      />

      {/* 上传信息提示 */}
      <div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
        {selectedImages.length > 0 ? (
          <span>
            已选择 {selectedImages.length}/{maxImages} 张图片， 总大小{" "}
            {formatFileSize(calculateTotalSize(selectedImages))}/{maxTotalSize}
            MB
          </span>
        ) : (
          <span>
            最多可上传 {maxImages} 张图片，每张不超过 {maxSizePerImage}
            MB，总大小不超过 {maxTotalSize}MB
          </span>
        )}
      </div>
    </div>
  );
};

export default ImageUploader;
